<?php
/**
 * Created by PhpStorm.
 * User: rain
 * Date: 2018/4/5
 * Time: 下午4:51
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\User;
use App\Utils\OfficialAccountUtil;
use Illuminate\Http\Request;
use EasyWeChat\Kernel\Messages\Raw;
use EasyWeChat\Kernel\Messages\Image;
use EasyWeChat\Kernel\Messages\Text;
use Illuminate\Support\Facades\Auth;

class OfficialController extends Controller
{
    private $officialAccountUtil;

    public function __construct(OfficialAccountUtil $officialAccountUtil)
    {
        $this->officialAccountUtil = $officialAccountUtil;
    }

    /**
     * 公众号消息回调
     * @param \Illuminate\Http\Request $request
     * @return mixed|\Symfony\Component\HttpFoundation\Response
     * @throws \EasyWeChat\Kernel\Exceptions\BadRequestException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function message(Request $request)
    {
        if ($request->isMethod('GET')){
            return $request->get('echostr', '验证字符串');
        }

        $app = $this->officialAccountUtil->getApp();
        $officialAccountUtil = $this->officialAccountUtil;
        $app->server->push(function ($message) use ($app, $officialAccountUtil){

            $openId = $message['FromUserName'];

            if (isset($message['MsgType'], $message['Event']) && $message['MsgType'] == 'event' && $message['Event'] == 'unsubscribe'){
                //取消关注
            }

            //$userInfo = $app->user->get($openId);//该接口每天调用次数有限制
            //$data = [
            //    'unionId' => $userInfo['unionid'],//unionId没有绑定开放平台则没有
            //    'openId' => $userInfo['openid'],
            //    'nickName' => $userInfo['nickname'],
            //    'avatarUrl' => $userInfo['headimgurl'],
            //    'follow_official' => 1,
            //];


            switch($message['MsgType']){
                case 'event':
                    switch($message['Event']){
                        case 'subscribe'://订阅
                        case 'SCAN'://通过扫码关注，并且已经关注返回的Event
                            //关注事件测试
                            //1、正常关注


                            //回复文字
                            $text = new Text("点击下方，即可马上领现金红包👇！");
                            $app->customer_service->message($text)->to($openId)->send();


                            //回复小程序卡片
                            $mediaId = $officialAccountUtil->getForeverImageMediaId();
                            $resData = [
                                'touser' => $message['FromUserName'],
                                'msgtype' => 'miniprogrampage',
                                'miniprogrampage' => [
                                    'title' => '［微信红包］恭喜发财，大吉大利',
                                    'appid' => 'wx2e5fa9d0066f2ea1',
                                    'pagepath' => 'pages/activity/lottery/square/index?ald_media_id=6016&ald_link_key=c9af8b7ae63b8ea8',
                                    'thumb_media_id' => $mediaId,
                                ],
                            ];

                            $data = new Raw(json_encode($resData, true));
                            $app->customer_service->message($data)->to($openId)->send();

                            return 'success';
                            break;

                        case 'unsubscribe':
                            //取消关注
                            //$userInfo = $app->user->get($openId);
                            //if (isset($userInfo['unionid'])){
                            //
                            //}
                            break;
                        case 'CLICK':
                            //$eventKey = $message['EventKey']; 不同的eventKey触发不同的事件

                            //回复图片
                            $mediaId = $officialAccountUtil->getForeverImageMediaId('images/mamiwechat.png');
                            $image = new Image($mediaId);
                            $app->customer_service->message($image)->to($message['FromUserName'])->send();

                            return 'success';
                            break;
                        default:
                            //其他事件暂时不处理
                            break;
                    }

                    return 'success';
                    break;
                case 'text'://收到文字消息
                case 'image'://收到图片消息
                case 'voice'://收到语音消息
                case 'video'://收到视频消息
                case 'location'://收到坐标消息
                case 'link'://收到链接消息
                case 'file'://收到文件消息
                    return 'success';
                default:
                    return 'success';
                    break;
            }
        });

        $response = $app->server->serve();

        return $response;
    }


    /**
     * 登录授权
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|\Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function auth(Request $request)
    {
        if (env('APP_ENV') == 'local'){
            //本地测试
            $user = User::find(1);
            Auth::login($user);
            //Auth::logout();
        }

        if (Auth::check()){
            return redirect('登陆后跳转的地址');
        }

        $app = $this->officialAccountUtil->getApp();
        $url = $request->getUri();
        $code = $request->get('code', '');
        if (empty($code)){
            $response = $app->oauth->scopes(['snsapi_userinfo'])->redirect($url);

            return $response;
        }
        try{
            $wxUser = $app->oauth->user();
            // $wxUser 可以用的方法:
            // $wxUser->getId();  // 对应微信的 OPENID
            // $wxUser->getNickname(); // 对应微信的 nickname
            // $wxUser->getName(); // 对应微信的 nickname
            // $wxUser->getAvatar(); // 头像网址
            // $wxUser->getOriginal(); // 原始API返回的结果
            // $wxUser->getToken(); // access_token， 比如用于地址共享时使用
            $userInfo = $wxUser->getOriginal();

            $inviteUserId = $request->get('userId', 0);//邀请人用户ID
            $data = [
                'unionId' => $userInfo['unionid'],
                'openId' => $userInfo['openid'],
                'nickName' => $userInfo['nickname'],
                'avatarUrl' => $userInfo['headimgurl'],
            ];

            $user = '用户注册';
            Auth::login($user);

            return redirect('登陆后跳转的地址');
        }catch(\Exception $e){

            return redirect($url);
        }


    }

}